import requests

import io

from fontTools.ttLib import TTFont

from PIL import Image , ImageFont,ImageDraw

from  ddddocr import DdddOcr


def get_font_maps(path):
    # 指定解析字体文件
    font = TTFont(path)

    # 指定绘制的字体文件
    img_font = ImageFont.truetype(path, 10)

    font_map = {}

    for code, name in font.getBestCmap().items():
        if code == 120:
            continue

        # 创建图片
        img = Image.new("RGB", (32, 32), (255, 255, 255))

        # 绘制图片
        draw = ImageDraw.Draw(img)
        draw.text((0, 0), chr(code), font=img_font, fill=(0, 0, 0))

        # 保存 图片
        # img.save(f"./static/font/img/{code}.png")
        img_bytes = io.BytesIO()
        img.save(img_bytes, "JPEG")

        ocr = DdddOcr(show_ad=False)
        r = ocr.classification(img_bytes.getvalue())

        # 添加特殊处理：如果识别为'i'且应该是数字，则替换为'1'
        if r == 'i':
            # 可以通过图像特征进一步判断是否应该为'1'
            # 这里简单处理，可以根据实际需求调整
            r = '1'

        font_map[code] = r
    return font_map


font_maps=get_font_maps("./static/font/96fc7b50b772f52.woff2")


def parse_field(value):

    result = ""
    for c in value:
        if ord(c) in font_maps:
            result += font_maps[ord(c)]
        else:
            result += c
    return result


# print(parse_field(".D a.4D"))



headers = {

    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",

}

url = "https://www.dongchedi.com/motor/pc/sh/sh_sku_list?aid=1839&app_name=auto_web_pc"

response = requests.post(url, headers=headers)

for item in response.json()["data"]['search_sh_sku_info_list']:
    print(item['car_name'], parse_field(item['car_source_city_name']), parse_field(item['official_price']), parse_field(item['sh_price']))




